package com.clay.appointment.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.clay.appointment.entity.dict.Dict;
import com.clay.appointment.mapper.DictMapper;
import com.clay.appointment.vo.dict.DictExcelVO;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author : clay
 * @Description:
 * @Date: Create in 16:03 2021/7/26
 * @Modified By:
 */
public class DictListener extends AnalysisEventListener<DictExcelVO> {

    private final DictMapper dictMapper;

    private List<DictExcelVO> dictList = new ArrayList<>();

    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }


    @Override
    public void invoke(DictExcelVO data, AnalysisContext context) {
        dictList.add(data);
        if (dictList.size() >= 100) {
            for (DictExcelVO dictExcelVO : dictList) {
                //调用方法添加到数据库中
                Dict dict = new Dict();
                BeanUtils.copyProperties(dictExcelVO, dict);
                dictMapper.insert(dict);
            }

            dictList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (!dictList.isEmpty()) {
            for (DictExcelVO dictExcelVO : dictList) {
                //调用方法添加到数据库中
                Dict dict = new Dict();
                BeanUtils.copyProperties(dictExcelVO, dict);
                dictMapper.insert(dict);
            }
        }
    }
}
